package com.heima.comment.service.impl;

import com.heima.comment.service.CommentHotService;
import com.heima.model.comment.pojo.ApComment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CommentHotServiceImpl implements CommentHotService {
    //查询热点文章

    @Autowired
    MongoTemplate mongoTemplate;
    @Async("taskExecutor")//当前方法需要异步执行,指定当前方法由哪个线程池执行
    @Override
    public void hotCommentExecutor(Long entryId, ApComment apComment) {
        //1.按照文章id,flag=1,点赞降序   查询所有的热点评论

        Query query = Query.query(Criteria.where("entryId").is(entryId).and("flag").is(1)).with(Sort.by(Sort.Direction.DESC, "likes"));
        List<ApComment> apHotComments = mongoTemplate.find(query, ApComment.class);

        //如果热评集合为空   或者数量小于5时  直接将当前评论转为热点评论

        if (apHotComments==null||apHotComments.size()<5){

            apComment.setFlag((short)1);
            mongoTemplate.save(apComment);
            return;//不用向下执行的   加return

        }

        //比较热点文章最后一条的点赞数

        ApComment comment = apHotComments.get(apHotComments.size() - 1);
        if (comment.getLikes()<apComment.getLikes()){
            comment.setFlag((short)0);
            apComment.setFlag((short)1);
            mongoTemplate.save(comment);
            mongoTemplate.save(apComment);
        }


    }
}
